/**
 * 
 */
package fhq.hcmute.edu.vn.network;

import java.awt.Component;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

import fhq.hcmute.edu.vn.gui.ServerGUI;

/**
 * @author nglehien Nov 5, 2012 - 4:18:10 PM
 */
public class Server {
	private ServerSocket serverSocket = null;
	private ComputerInfos serverInfo;
	private Component component;
	private Connection connection;
	private Thread serverThread;
	private boolean isStarted = false;

	public Server(Component component, ComputerInfos serverInfo) {
		this.serverInfo = serverInfo;
		this.component = component;
		try {
			serverSocket = new ServerSocket(serverInfo.getPort());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void start() throws IOException {
		isStarted = true;
		serverThread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					ServerGUI.lblServerState.setText("Server is Ready");
					Socket socket = serverSocket.accept();
					socket.setKeepAlive(true);
					socket.setTcpNoDelay(true);
					connection = new Connection(socket, Server.this);
					connection.setComponent(component);
					connection.setServerInfo(serverInfo);
				} catch (SocketException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		serverThread.start();
	}

	public void stop() throws IOException {
		if (connection != null) {
			connection.closeClientConnection();
		}
		connection = null;
		if (!serverThread.isInterrupted()) {
			serverThread.interrupt();
		}
		serverThread = null;
		ServerGUI.updateServerInfos();
		isStarted = false;
		ServerGUI.lblServerState.setText("");
		serverSocket = null;
		ServerGUI.setServer(null);
	}

	public boolean isStarted() {
		return isStarted;
	}

	public void setStarted(boolean isStarted) {
		this.isStarted = isStarted;
	}
}
